<script setup lang="jsx">
  import {watch,inject,ref,nextTick,reactive,computed} from 'vue'
import { Message, Modal } from '@arco-design/web-vue'
import tool from '@/utils/tool'
import shipment from '@/api/document/shipment'
import commonApi from '@/api/common'
import uploadConfig from '@/config/upload'
import { color } from 'echarts'
const columnsDist = inject('columnsDist')
const fileVisible=ref(false)
const formFileRef=ref(null)
const title=ref('')
const formFileData=ref({
  type:'',
  user_id:'',
  fileList:[],

})
const loadingUp=ref(false)
const showFileList=ref([])
/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
//   open: false,
  // 弹出层标题（用户导入）
  title: "",
  fileList:[],
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + tool.getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_URL + "/system/uploadFile"
});
//下载模版
const downloadImportTemplate = async () => {
  let res = await shipment.downloadTemplate({type: formFileData.value.type})
  let url = res.data.url
  let storeMode = 'OSS'

  Message.info('处理中...')
  const domain = uploadConfig.storage[storeMode]
  url = domain + url

  const response = await commonApi.download(url, 'get')
  if (response) {
    tool.download(response, (storeMode !== 'LOCAL') ? res.data.origin_name : '')
    Message.success('请求成功，文件开始下载')
  } else {
    Message.error('文件下载失败')
  }
}
//上传前判断
const beforeUpload=(file)=>{
   if (file.size / 1024 / 1024 > 5) {
    Message.error('上传文件大小不能超过5M!')
      return false;
   }
   return true
}
const handleUpload = (fileList, files) => {
  loadingUp.value = true
  if (!files.file) {
    Modal.open({content: '没有选择文件'})
    loadingUp.value = false
    return
  }
  if(files?.response?.data.hash){
  let result=files?.response?.data
      result.url = tool.attachUrl(result.url, uploadConfig.storageMode[result.storage_mode])
    showFileList.value.push(result)
    let data={
      type:formFileData.value.type,
      user_id:formFileData.value.user_id,
      file:result.hash,
    }
    shipment.importExcel(data).then(res => {
      result.message=res.message || '上传成功'
      result.success=res.success
      loadingUp.value = false

    }).catch((error) => {
      result.message=error.message || '上传失败'
      result.success=error.success
      loadingUp.value = false
    });
  }

};
//删除
const removeFile = (idx) => {
  showFileList.value.splice(idx, 1)
  let files = []
  files = showFileList.value.map(item => {
    return item[config.returnType]
  })
  // emit('update:modelValue', files)
}
// 上传数据
const rulesFile = {
      user_id: [{ required: true, message:'请选择用户',validateTrigger: 'blur'}, ],
      fileList: [{ required: true, message:'请上传文件',validateTrigger: 'blur'}, ],
  }
  const onShow = async (value) => {
    formFileData.value.fileList=[]
    formFileData.value.type=value
    if(value=='shipment_excel'){
      title.value='导入运单'
    }else if(value=='shipment_excel_batch'){
      title.value='批量导入'

    }else if(value=='shipment_excel_batch_draft'){
      title.value='草稿导入'
    }
    fileVisible.value = true
  }
const emits = defineEmits(['addClick'])
  //新增 
const submitForm =async (formEl) => {
  if (!formEl) return
    await formEl.validate((valid) => {
      if (!valid) {
            emits('addClick');
            close()         
      }
    }) 
    
  };

    const close = () => {
      fileVisible.value = false
      showFileList.value=[]
      formFileData.value.type=''
      formFileData.value.user_id=''
      formFileData.value.fileList=[]
      title.value=''
    }
defineExpose({ onShow })
</script>

<template>
      <a-modal v-model:visible="fileVisible" :title="title" v-if="fileVisible" :esc-to-close="false" @cancel="close">
        <a-spin dot class="spin" v-if="loadingUp"  :loading="loadingUp"></a-spin>
        <a-form ref="formFileRef" :rules="rulesFile" :model="formFileData" auto-label-width >
              <a-form-item field="user_id" label="用户" validate-trigger="change">
                <a-select v-model="formFileData.user_id" :options="columnsDist.dicthelpApi_customer.data" :field-names="{ value: 'id', label: 'nick' }"
                placeholder="请选择用户" allow-clear allow-search :virtual-list-props="{height:200}" /> 
              </a-form-item>
              <a-form-item field="fileList" label="文件" validate-trigger="change">
                <a-upload :disabled="formFileData.user_id==''" v-model:file-list="formFileData.fileList" @before-upload="beforeUpload" @change="handleUpload" :action="upload.url" multiple :headers="upload.headers"
                :show-file-list="false"
                />
                <a-button  @click="downloadImportTemplate()" style="margin-left: 20px;">下载模版</a-button>                
              </a-form-item>
              <div class="main-list">
              <div
                  class="file-list mt-2"
                  v-for="(file, idx) in showFileList" :key="idx"
                >
                  <a-tooltip content="点击文件名预览/下载" position="tr">
                    <a :href="file.url"
                      v-if="file?.url"
                      class="file-name"
                      target="_blank"
                    >{{ file.origin_name }}</a>
                  </a-tooltip>
                  <span  :style="{'color' : file.success ? 'green':'red'}">{{file.message}}</span>
                  <!-- <a-button
                    type="text"
                    size="small"
                    @click="removeFile(idx)"
                  >
                    <template #icon>
                      <icon-delete/>
                    </template>
                  </a-button> -->
                </div>
              </div>
         </a-form>

         <template #footer>        
          <a-button @click="close">关闭</a-button>
          <a-button type="primary" @click="submitForm(formFileRef)">
            确定
          </a-button>
        </template>
    </a-modal>
  
</template>
<style lang="less" scoped>
.main-list{
  max-height: 300px;
  overflow-y: auto;
}
.file-list {
  background-color: var(--color-primary-light-1);
  border-radius: 4px;
  height: 36px;
  padding: 0 5px;
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;

  .file-name {
    max-width: 80%;
    margin: 0 5px;
    overflow: hidden;
    color: #165DFF;
  }
}
.spin{
  position: fixed;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index:10000;
}
</style>